<template>
	<div v-loading="loading" class="app-main-content-box">
		<!-- 标题 -->
		<div class="app-main-top-box">
			<div class="title">{{ form.onlyMemberDay ? '会员日' : '' }}{{ $store.state.setting.marketingActivityTypeKeyOptions[form.activityType] || '-' }}</div>
			<el-button size="medium" round @click="back">返回</el-button>
		</div>

		<!--    会员日提示-->

		<div v-if="form.onlyMemberDay" class="app-main-tips-box">
			<div class="title">
				<i class="el-icon-warning" />
				会员日
			</div>
			<ul>
				<li v-if="memberDayList.length" class="member-day-list">
					<span v-for="(item, index) in memberDayList" :key="item.right.id">
						<span v-if="item.right.dateType === 1 && index === 0">每个自然月：</span>
						<span v-if="index !== 0">、</span>
						<span v-if="item.right.dateType === 1">{{ item.right.date }}日</span>
						<span v-if="item.right.dateType === 2 && index === 0">每个自然周：</span>
						<span v-if="item.right.dateType === 2">{{ weekKeyOptions[item.right.date] }}</span>
					</span>
					<span>，</span>
					<a href class="btn" @click.prevent="jumpVipBenefitMemberDay"><u>去配置会员日</u></a>
					。
				</li>
				<li v-else>
					会员日营销需先配置会员日，当前未配置，
					<a href class="btn" @click.prevent="jumpVipBenefitMemberDay"><u>去配置会员日</u></a>
					。
				</li>
			</ul>
		</div>

		<el-form ref="form" :model="form" :rules="rules" class="content" size="small" label-width="150px">
			<!-- 基础信息  开始-->
			<el-divider content-position="left">基础信息</el-divider>
			<!-- 主题 -->
			<el-form-item label="活动主题：" prop="theme"><el-input v-model="form.theme" class="w-500" maxlength="30" show-word-limit /></el-form-item>

			<!-- 封面 -->
			<el-form-item label="活动封面：" prop="image">
				<el-upload
					:show-file-list="false"
					:action="actionUrl"
					:headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
					:on-success="uploadImageSuccess"
					:before-upload="beforeUploadImage"
					class="app-uploader-img-plus upload-poster-img"
				>
					<img v-if="form.image" :src="fileBaseUrl + form.image" class="upload-img" alt />
					<i v-else class="el-icon-plus upload-icon-plus" />
				</el-upload>
				<div class="upload-card-tips">
					<div>1.只能上传jpg/png文件，且不超过1MB</div>
					<div>2.建议尺寸750*440像素</div>
				</div>
			</el-form-item>

			<el-form-item label="活动时间：" class="is-required">
				<el-form-item prop="date">
					<el-date-picker
						v-model="form.date"
						:picker-options="datePickerOptions"
						type="daterange"
						range-separator="~"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						value-format="yyyy-MM-dd"
						format="yyyy-MM-dd"
					/>
				</el-form-item>
				<div v-if="!form.onlyMemberDay">
					<!-- 时间类型一 -->
					<el-radio v-model="form.useRule" :label="1">有效期内所有时间都可以参与活动</el-radio>
					<br />
					<!-- 时间类型二 -->
					<el-radio v-model="form.useRule" :label="2">有效期内，规则日期可用</el-radio>
					<br />
					<el-collapse-transition>
						<div v-if="form.useRule === 2" class="nest-card-box">
							<el-card>
								<el-form-item prop="ruleDataWeek">
									<el-checkbox-group v-model="form.ruleDataWeek">
										<el-checkbox-button v-for="(dayItem, dayIndex) in weekOptions" :key="dayIndex" :label="String(dayItem.label)">
											{{ dayItem.value }}
										</el-checkbox-button>
									</el-checkbox-group>
								</el-form-item>
								<el-form-item prop="ruleDataTime">
									<div v-for="(item, index) in form.ruleDataTime" :key="'time' + index" class="date-picker-box">
										<el-time-picker
											v-model="form.ruleDataTime[index].time"
											is-range
											value-format="HH:mm"
											format="HH:mm"
											range-separator="~"
											start-placeholder="开始时间"
											end-placeholder="结束时间"
											placeholder="选择时间范围"
										/>
										<el-button
											v-if="form.ruleDataTime.length > 1 && index + 1 === form.ruleDataTime.length"
											type="text"
											icon="el-icon-delete"
											class="app-text-color-danger"
											@click="delAvailablePeriodTime(index)"
										>
											删除
										</el-button>
										<el-button
											v-if="form.ruleDataTime.length === index + 1 && form.ruleDataTime.length < 3"
											type="text"
											icon="el-icon-plus"
											class="app-text-color-primary"
											@click="addAvailablePeriodTime"
										>
											添加
										</el-button>
									</div>
								</el-form-item>
								<div class="tips-info">请按照24小时制输入可用时段，最多设置3个时段</div>
							</el-card>
						</div>
					</el-collapse-transition>
					<!-- 时间类型三 -->

					<el-radio v-model="form.useRule" :label="3">有效期内，不规则日期可用</el-radio>

					<el-collapse-transition>
						<div v-if="form.useRule === 3" class="nest-card-box">
							<el-card>
								<div class="tips-info">可在有效期内任意选择时间天数，以及可用时段。</div>
								<div class="tips-info">因当前系统支持问题，如选择不规则时间，卡包内当前仅会展示有效期，建议</div>
								<div class="tips-info">将具体可用日期以及时间段填写在代金券使用说明内。</div>
								<el-form-item prop="ruleDataDate">
									<div v-for="(item, index) in form.ruleDataDate" :key="'date' + index" class="date-picker-box">
										<el-date-picker
											v-model="form.ruleDataDate[index].date"
											type="daterange"
											range-separator="~"
											start-placeholder="开始日期"
											end-placeholder="结束日期"
											value-format="yyyy-MM-dd"
											format="yyyy-MM-dd"
											size="small"
										/>
										<el-button
											v-if="form.ruleDataDate.length > 1 && index + 1 === form.ruleDataDate.length"
											type="text"
											icon="el-icon-delete"
											class="app-text-color-danger"
											@click="delAvailablePeriodDate(index)"
										>
											删除
										</el-button>
										<el-button
											v-if="form.ruleDataDate.length === index + 1"
											type="text"
											icon="el-icon-plus"
											class="app-text-color-primary"
											@click="addAvailablePeriodDate"
										>
											添加
										</el-button>
									</div>
								</el-form-item>
								<el-form-item prop="ruleDataTime">
									<div v-for="(item, index) in form.ruleDataTime" :key="index" class="date-picker-box">
										<el-time-picker
											v-model="form.ruleDataTime[index].time"
											is-range
											value-format="HH:mm"
											format="HH:mm"
											range-separator="~"
											start-placeholder="开始时间"
											end-placeholder="结束时间"
											placeholder="选择时间范围"
										/>
										<el-button
											v-if="form.ruleDataTime.length > 1 && index + 1 === form.ruleDataTime.length"
											type="text"
											icon="el-icon-delete"
											class="app-text-color-danger"
											@click="delAvailablePeriodTime(index)"
										>
											删除
										</el-button>
										<el-button
											v-if="form.ruleDataTime.length === index + 1 && form.ruleDataTime.length < 3"
											type="text"
											icon="el-icon-plus"
											class="app-text-color-primary"
											@click="addAvailablePeriodTime"
										>
											添加
										</el-button>
									</div>
								</el-form-item>
								<div class="tips-info">请按照24小时制输入可用时段，最多设置3个时段</div>
							</el-card>
						</div>
					</el-collapse-transition>
				</div>
			</el-form-item>
			<!-- 基础信息  结束-->

			<!-- 活动规则 开始 -->
			<el-divider content-position="left">活动规则</el-divider>
			<!-- 参与对象 -->
			<el-form-item label="参与对象：" prop="memberCategory">
				<el-radio v-model="form.participant" :label="1" :disabled="form.onlyMemberDay === true" @change="participantChange">所有人</el-radio>
				<el-radio v-model="form.participant" :label="2" @change="participantChange">所有会员</el-radio>
				<el-radio v-model="form.participant" :label="3" @change="participantChange">指定会员等级</el-radio>
				<el-radio v-model="form.participant" :label="4" @change="participantChange">指定手机用户</el-radio>
				<el-radio v-if="form.activityType === 4" v-model="form.participant" :label="5" @change="participantChange">指定银行卡用户</el-radio>
				<el-radio v-if="form.activityType != 3 && judgeOpen == 1" v-model="form.participant" :label="6" @change="participantChange">指定会员分群</el-radio>
				<el-collapse-transition>
					<div v-if="form.participant === 3" class="nest-card-box">
						<el-card>
							<el-checkbox-group v-model="form.memberCategory">
								<el-checkbox v-for="item in cardList" :key="item.id" :label="String(item.id)">
									{{ item.status ? item.categoryName : item.categoryName + '(已停用)' }}
								</el-checkbox>
							</el-checkbox-group>
						</el-card>
					</div>
					<div v-if="form.participant === 6" class="nest-card-box">
						<el-card>
							<el-checkbox-group v-model="form.memberCategory">
								<el-checkbox v-for="item in memberGroup" :key="item.id" :label="String(item.id)">
									{{ item.groupName }}
									<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
										<div slot="content">{{ item.txt }}</div>
										<i class="el-icon-warning app-text-color-info" />
									</el-tooltip>
								</el-checkbox>
							</el-checkbox-group>
						</el-card>
					</div>
				</el-collapse-transition>
			</el-form-item>
			<div v-if="form.participant === 4">
				<div>
					<el-form-item label="手机用户名单：" prop="phoneListKey">
						<el-button type="primary" round size="small" @click="openDialogUploadPhoneListKey('phone')">上传</el-button>
						<span v-if="form.phoneListKey">&nbsp;文件名：{{ form.phoneListKey }}</span>
					</el-form-item>
					<div v-if="form.activityType === 4">
						<el-form-item label="手机号匹配精度：" prop="matchPrecision1">
							<el-input v-model="form.matchPrecision1" maxlength="2" class="w-200" placeholder="请输入正整数">
								<template slot="append">
									位
								</template>
							</el-input>
						</el-form-item>
					</div>
				</div>
			</div>
			<div v-if="form.participant === 5">
				<div>
					<el-form-item label="银行名称：" prop="specificBank">
						<el-input v-model="form.specificBank" placeholder="请输入银行/卡片名称" class="w-500" maxlength="8" show-word-limit />
					</el-form-item>
					<el-form-item label="持卡人信息：" prop="phoneListKey">
						<el-button type="primary" round size="small" @click="openDialogUploadPhoneListKey('bank')">上传</el-button>
						<span v-if="form.phoneListKey">&nbsp;{{ form.phoneListKey }}</span>
					</el-form-item>
					<div v-if="form.activityType === 4">
						<el-form-item label="手机号匹配精度：" prop="matchPrecision1">
							<el-input v-model="form.matchPrecision1" maxlength="2" class="w-200" placeholder="请输入正整数">
								<template slot="append">
									位
								</template>
							</el-input>
						</el-form-item>
						<el-form-item label="银行卡匹配精度：" prop="matchPrecision2">
							<el-input v-model="form.matchPrecision2" maxlength="2" class="w-200" placeholder="请输入正整数">
								<template slot="append">
									位
								</template>
							</el-input>
						</el-form-item>
					</div>
				</div>
			</div>

			<!-- 类型一规则类型 -->
			<div v-if="form.activityType === 1 || form.activityType === 3">
				<el-form-item label="规则类型：" class="is-required">
					<el-radio v-model="form.calculateTypeExtra" :label="1" :disabled="!!form.id">
						<span v-if="form.activityType === 1">按阶梯赠礼</span>
						<span v-if="form.activityType === 3">按阶梯返微信红包</span>
						<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
							<div slot="content">消费达到设定门槛才送，不累计，可设置多个消费门槛。</div>
							<i class="el-icon-warning app-text-color-info" />
						</el-tooltip>
					</el-radio>
					<el-radio v-model="form.calculateTypeExtra" :label="2" :disabled="!!form.id">
						<span v-if="form.activityType === 1">消费每满赠礼</span>
						<span v-if="form.activityType === 3">支付每满返微信红包</span>
						<el-tooltip popper-class="el-tooltip-theme-fresh" placement="top" effect="light">
							<div slot="content">
								消费达到设定门槛送，如设定消费100元送10元，则消费
								<br />
								200元时候，自动送20元，只可以设置一个消费门槛。
							</div>
							<i class="el-icon-warning app-text-color-info" />
						</el-tooltip>
					</el-radio>
				</el-form-item>
			</div>

			<!-- 活动规则 start-->
			<div v-if="[1, 2, 3, 4].includes(form.activityType)">
				<el-form-item label="规则配置：" prop="award">
					<!--消费满额赠礼-->
					<div v-if="form.activityType === 1">
						<!--  <el-table> 的 key="id_a"随意命名，必须独立。 -->
						<el-table key="id_a" :data="form.award" border stripe size="small" empty-text="暂未配置" style="width: 800px">
							<el-table-column label="消费金额/元" width="180">
								<template slot-scope="scope">
									{{ scope.row.amount }}
								</template>
							</el-table-column>
							<el-table-column label="赠礼">
								<template slot-scope="scope">
									<div v-if="scope.row.awardTypeExtra.includes('bonusBalance')">
										<span class="award-type-icon award-type-icon-balance">金</span>
										按照固定金额赠送{{ scope.row.balance }}元
									</div>
									<div v-if="scope.row.awardTypeExtra.includes('bonusPoint')">
										<span class="award-type-icon award-type-icon-point">积</span>
										赠送积分{{ scope.row.points }}个
									</div>
									<div v-if="scope.row.awardTypeExtra.includes('bonusCardCoupon') || scope.row.awardTypeExtra.includes('bonusCoupon')">
										<div v-for="(couponItem, couponIndex) in scope.row.couponData" :key="couponIndex">
											<span class="award-type-icon award-type-icon-coupon">
												<span v-if="['times', 'gift'].includes(couponItem.couponType)">卡</span>
												<span v-else>券</span>
											</span>
											赠送卡券{{ '【' + couponItem.name + '】' + couponItem.num }}张
										</div>
									</div>
								</template>
							</el-table-column>
							<el-table-column v-if="!form.id" label="操作" width="180">
								<template slot-scope="scope">
									<el-button type="text" size="small" @click.native.prevent="editRuleRow(scope.$index, scope.row)">编辑</el-button>
									<el-button type="text" size="small" @click.native.prevent="delRuleRow(scope.$index, scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>

						<!-- v-if="!form.id" 导致修改不显示按钮-->
						<el-button
							:disabled="form.calculateTypeExtra === 2 && form.award.length >= 1"
							type="text"
							icon="el-icon-plus"
							style="display:block"
							@click.native.prevent="addRuleRow"
						>
							增加规则
						</el-button>
					</div>
					<!--支付后返现到微信红包-->
					<div v-if="form.activityType === 3">
						<el-table v-if="!form.id" key="id_b" :data="form.award" border stripe size="small" empty-text="暂未配置" style="width: 800px">
							<el-table-column label="消费金额/元">
								<template slot-scope="scope" :rules="rules.amount">
									<el-form-item :prop="'award.' + scope.$index + '.amount'" :rules="rules.amount">
										<el-input v-model.trim="scope.row.amount" maxlength="10" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column label="红包金额/元">
								<template slot-scope="scope">
									<el-form-item :prop="'award.' + scope.$index + '.balance'" :rules="rules.balance">
										<el-input v-model.trim="scope.row.balance" maxlength="10" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column v-if="!form.id" label="操作" width="100">
								<template slot-scope="scope">
									<el-button type="text" size="small" @click.native.prevent="delRuleRow(scope.$index, scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-table v-else key="id_c" :data="form.award" border stripe size="small" empty-text="暂未配置" style="width: 800px">
							<el-table-column prop="amount" label="消费金额/元" />
							<el-table-column prop="balance" label="红包金额/元" />
						</el-table>
						<el-button
							v-if="!form.id"
							:disabled="form.calculateTypeExtra === 2 && form.award.length >= 1"
							type="text"
							icon="el-icon-plus"
							style="display:block"
							@click.native.prevent="addRuleRow"
						>
							增加规则
						</el-button>
					</div>

					<!--领券活动-->
					<div v-if="form.activityType === 4">
						<el-table key="id_d" :data="(form.award.length && form.award[0].couponData) || []" border stripe size="small" empty-text="暂未配置" style="width: 800px">
							<el-table-column prop="couponId" label="批次号" width="180" />
							<el-table-column prop="name" label="卡券名称" />
							<el-table-column prop="couponType" label="卡券类型">
								<template slot-scope="scope">
									{{ $store.getters.cardCouponTypeKeyOptions[scope.row.couponType] }}
								</template>
							</el-table-column>
							<el-table-column prop="num" label="数量" width="170">
								<template slot-scope="scope">
									<el-form-item :prop="'award.0.couponData.' + scope.$index + '.num'" :rules="rules.couponNum">
										<el-input-number v-model="scope.row.num" :min="1" :max="99" maxlength="2" label="数量" />
									</el-form-item>
								</template>
							</el-table-column>
							<el-table-column v-if="!form.id" label="操作" width="60">
								<template slot-scope="scope">
									<el-button type="text" size="small" @click.native.prevent="delRuleRow(scope.$index, scope.row)">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
						<el-button
							v-if="!form.id"
							:disabled="form.calculateTypeExtra === 2 && form.award.length >= 1"
							type="text"
							icon="el-icon-plus"
							style="display:block"
							@click.native.prevent="addRuleRow"
						>
							增加卡券
						</el-button>
						<div style="color:#909399;font-size: 12px;">
							单次最多添加券种类不超过10种，券总数量不超过30张（因为微信限制，如果你选择了微信商家券则此活动所有卡券必须是微信商家券且券总数量不超过10张）
						</div>
					</div>
				</el-form-item>
			</div>

			<div v-if="[5, 6, 7, 8].includes(form.activityType)">
				<el-form-item label="规则配置：" prop="singleRules">
					<!-- 单品立减 start-->
					<div v-if="form.activityType === 5">
						<div v-for="(item, index) in form.singleRules" :key="'rules_' + index">
							<div>
								<span>活动商品编码任意一个或多个消费满&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesThreshold" class="app-display-i-b">
									<el-input v-model="item.threshold" maxlength="10" class="w-200" placeholder="请输入">
										<template slot="append">
											元
										</template>
									</el-input>
								</el-form-item>
								<span>&nbsp;立减&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesAmount" class="app-display-i-b">
									<el-input v-model="item.amount" maxlength="10" class="w-200" placeholder="请输入">
										<template slot="append">
											元
										</template>
									</el-input>
								</el-form-item>
								<el-button v-if="form.singleRules.length > 1" type="text" size="small" @click.native.prevent="delRuleRow(index)">删除</el-button>
							</div>
						</div>
						<el-button v-if="!form.id" type="text" icon="el-icon-plus" style="display:block" @click.native.prevent="addRuleRow">增加规则</el-button>
					</div>
					<!-- 单品立减 end-->

					<!-- 单品立减 start-->
					<div v-if="form.activityType === 6">
						<div v-for="(item, index) in form.singleRules" :key="'rules_' + index">
							<div>
								<span>每一个商品国际条码买&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesThreshold" class="app-display-i-b">
									<el-input v-model="item.threshold" maxlength="7" class="w-200" placeholder="请输入">
										<template slot="append">
											件
										</template>
									</el-input>
								</el-form-item>
								<span>&nbsp;件，其中&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesAmount" class="app-display-i-b">
									<el-input v-model="item.amount" maxlength="7" class="w-200" placeholder="请输入">
										<template slot="append">
											件
										</template>
									</el-input>
								</el-form-item>
								<span>&nbsp;免单</span>
								<el-button v-if="form.singleRules.length > 1" type="text" size="small" @click.native.prevent="delRuleRow(index)">删除</el-button>
							</div>
						</div>
						<div class="tips-info">1笔订单，同一商品满足门槛后仅送一次，不重复赠送</div>
						<div class="tips-info">1笔订单，多个商品分别满足门槛，则多个商品均送设置的件数</div>

						<el-button v-if="!form.id" type="text" icon="el-icon-plus" style="display:block" @click.native.prevent="addRuleRow">增加规则</el-button>
					</div>
					<!-- 单品立减 end-->

					<!-- 单品折扣 start-->
					<div v-if="form.activityType === 7">
						<div v-for="(item, index) in form.singleRules" :key="'rules_' + index">
							<div v-if="index === 0">
								<el-form-item>
									<el-select v-model="item.everyOne" placeholder="请选择" @change="everyOneChange">
										<el-option :value="false" label="第N件商品打折" />
										<el-option :value="true" label="每件商品都打折" />
									</el-select>
								</el-form-item>
							</div>
							<div>
								<span v-if="item.everyOne">购买同国际条码商品，满&nbsp;</span>
								<span v-else>购买同国际条码商品，仅第&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesThreshold" class="app-display-i-b">
									<el-input v-model="item.threshold" maxlength="7" class="w-200" placeholder="请输入">
										<template slot="append">
											件
										</template>
									</el-input>
								</el-form-item>
								<span v-if="item.everyOne">&nbsp;，或者更多时每件商品均享受&nbsp;</span>
								<span v-else>&nbsp;享受&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesAmount" class="app-display-i-b">
									<el-input v-model="item.amount" maxlength="3" class="w-200" placeholder="请输入">
										<template slot="append">
											折
										</template>
									</el-input>
								</el-form-item>
								<span>&nbsp;优惠</span>
								<el-button v-if="form.singleRules.length > 1" type="text" size="small" @click.native.prevent="delRuleRow(index)">删除</el-button>
							</div>
						</div>
						<div class="tips-info">1笔订单，同一商品满足门槛后折扣一次，不重复折扣</div>
						<div class="tips-info">1笔订单，多个商品国际条码分别满足优惠条件，则多个商品均有折扣</div>
						<el-button v-if="!form.id" type="text" icon="el-icon-plus" style="display:block" @click.native.prevent="addRuleRow">增加规则</el-button>
					</div>
					<!-- 单品折扣 end-->

					<!-- 单品折扣立减 start-->
					<div v-if="form.activityType === 8">
						<div v-for="(item, index) in form.singleRules" :key="'rules_' + index">
							<div v-if="index === 0">
								<el-form-item>
									<el-select v-model="item.everyOne" placeholder="请选择" @change="everyOneChange">
										<el-option :value="false" label="第N件商品立减到" />
										<el-option :value="true" label="每件商品都立减" />
									</el-select>
								</el-form-item>
							</div>
							<div>
								<span v-if="item.everyOne">购买同国际条码商品，满&nbsp;</span>
								<span v-else>购买同国际条码商品，仅第&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesThreshold" class="app-display-i-b">
									<el-input v-model="item.threshold" maxlength="7" class="w-200" placeholder="请输入">
										<template slot="append">
											件
										</template>
									</el-input>
								</el-form-item>
								<span v-if="item.everyOne">&nbsp;或者更多时每件商品均享受立减到&nbsp;</span>
								<span v-else>&nbsp;享受立减到&nbsp;</span>
								<el-form-item :prop="'singleRules.' + index" :rules="rules.singleRulesAmount" class="app-display-i-b">
									<el-input v-model="item.amount" maxlength="10" class="w-200" placeholder="请输入">
										<template slot="append">
											元
										</template>
									</el-input>
								</el-form-item>
								<el-button v-if="form.singleRules.length > 1" type="text" size="small" @click.native.prevent="delRuleRow(index)">删除</el-button>
							</div>
						</div>
						<el-button v-if="!form.id" type="text" icon="el-icon-plus" style="display:block" @click.native.prevent="addRuleRow">增加规则</el-button>
					</div>
					<!-- 单品立减折扣 end-->
				</el-form-item>
			</div>
			<!-- 活动规则 结束-->

			<!--规则补充 start-->
			<div v-if="[5, 6, 7, 8].includes(form.activityType)">
				<div>
					<el-form-item label="活动商品国际条码：" prop="singleGoods">
						<el-input v-model="form.singleGoods" :autosize="{ minRows: 5 }" class="w-500" type="textarea" placeholder="请输入" show-word-limit />
						<div class="tips-info">请输入商品国际条码，一行一个(Enter换行)，最多支持3000个</div>
						<!--<el-button-->
						<!--  type="text"-->
						<!--  icon="el-icon-plus"-->
						<!--  style="display:block"-->
						<!--  @click.native.prevent="openDialogMarketingGoodsTable"-->
						<!--&gt;从商城商品库添加-->
						<!--</el-button>-->
					</el-form-item>
					<el-form-item label="整单优惠同享开关：">
						<el-switch v-model="form.discountSharing" active-color="#13ce66" inactive-color="#ff4949" />
						<span>打开开关, 则单品通过该活动优惠后，商品优惠后的价格可以正常参与整单优惠的门槛计算和优惠</span>
					</el-form-item>
				</div>
			</div>
			<!--规则补充 end-->

			<!--规则补充 start-->
			<div v-if="form.activityType === 3">
				<el-form-item label="微信商户号：" prop="wxMchId">
					<el-input v-model="form.wxMchId" class="w-500" maxlength="20" show-word-limit />
					<div style="color:#909399;font-size: 12px;">请输入微信支付的商户号, 保存后请充值到该商户号方可实现发红包</div>
				</el-form-item>
				<el-form-item label="微信APPID：" prop="appId">
					<el-input v-model="form.appId" class="w-500" maxlength="20" show-word-limit />
					<div style="color:#909399;font-size: 12px;">请输入商户号对应的公众号，将会通过该公众号发送消息给顾客，如果顾客未关注公众号，将通过服务通知触达</div>
				</el-form-item>
				<el-form-item label="发送者名称：" prop="sender">
					<el-input v-model="form.sender" class="w-500" maxlength="20" show-word-limit />
					<div style="color:#909399;font-size: 12px;">红包封面-发送者名称或商户名称，最终效果为：{发送者名称}的红包</div>
				</el-form-item>
				<el-form-item label="祝福语：" prop="blessing">
					<el-input v-model="form.blessing" class="w-500" maxlength="20" show-word-limit />
					<div style="color:#909399;font-size: 12px;">例："恭喜发财，大吉大利"/"感谢您参加猜灯谜活动，祝您元宵节快乐！</div>
				</el-form-item>
			</div>
			<!--规则补充 end-->

			<!-- 活动限制  开始-->
			<el-divider content-position="left">活动限制</el-divider>

			<!-- 用户限制 -->
			<el-form-item label="参与活动限制：" class="is-required">
				<el-form-item prop="frequencyDay">
					<el-checkbox v-model="form.frequencyDayCheckedExtra">一个用户一天可参与活动&nbsp;</el-checkbox>
					<el-input v-model="form.frequencyDay" :disabled="!form.frequencyDayCheckedExtra" placeholder="请输入" maxlength="8" class="w-200">
						<template slot="append">
							次
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="frequencyWeek">
					<el-checkbox v-model="form.frequencyWeekCheckedExtra">一个用户一周可参与活动&nbsp;</el-checkbox>
					<el-input v-model="form.frequencyWeek" :disabled="!form.frequencyWeekCheckedExtra" placeholder="请输入" maxlength="8" class="w-200">
						<template slot="append">
							次
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="frequencyMonth">
					<el-checkbox v-model="form.frequencyMonthCheckedExtra">一个用户一月可参与活动&nbsp;</el-checkbox>
					<el-input v-model="form.frequencyMonth" :disabled="!form.frequencyMonthCheckedExtra" placeholder="请输入" maxlength="8" class="w-200">
						<template slot="append">
							次
						</template>
					</el-input>
				</el-form-item>
				<el-form-item prop="frequencyAll">
					<el-checkbox v-model="form.frequencyAllCheckedExtra">一个用户累计可参与活动&nbsp;</el-checkbox>
					<el-input v-model="form.frequencyAll" :disabled="!form.frequencyAllCheckedExtra" placeholder="请输入" maxlength="8" class="w-200">
						<template slot="append">
							次
						</template>
					</el-input>
				</el-form-item>
			</el-form-item>
			<!-- 活动预算 -->
			<el-form-item v-if="id" label="活动总预算：" prop="budget">
				<div />
				<div v-if="form.budgetCheckedExtra">
					<!-- <span>总预算 {{form.budget}}</span> -->
					<span>总预算 {{ form.budget }} 份，已投放 {{ form.budget - form.remainBudget }} 份， 剩余</span>
					<span class="app-text-color-danger">{{ form.remainBudget }}</span>
					份
				</div>
				<div v-else>无限制</div>
				<!-- <div>
          <el-button size="mini" round @click="modifyQuantity('add')">增加预算</el-button>
          <el-button size="mini" round @click="modifyQuantity('reduce')">减少预算</el-button>
        </div>-->
			</el-form-item>
			<el-form-item v-else label="活动总预算：" prop="budget">
				<el-checkbox v-model="form.budgetCheckedExtra">活动最大可被用户参与 &nbsp;&nbsp;&nbsp;&nbsp;</el-checkbox>
				<el-input v-model="form.budget" :disabled="!form.budgetCheckedExtra" placeholder="请输入" maxlength="8" class="w-200">
					<template slot="append">
						次
					</template>
				</el-input>
			</el-form-item>

			<el-form-item label="单天活动预算：" prop="perdayBudget">
				<el-checkbox v-model="form.perdayBudgetCheckedExtra">活动单天可被用户参与 &nbsp;&nbsp;&nbsp;&nbsp;</el-checkbox>
				<el-input v-model="form.perdayBudget" :disabled="!form.perdayBudgetCheckedExtra" placeholder="请输入" maxlength="8" class="w-200">
					<template slot="append">
						次
					</template>
				</el-input>
			</el-form-item>
			<el-form-item><div class="tips-info">温馨提示：以上活动限制不勾选则代表该选项无限制</div></el-form-item>
			<!-- 活动限制  结束-->

			<!-- 高级设置  开始-->
			<el-divider content-position="left">高级设置</el-divider>
			<div class="app-main-filter-collapse-box">
				<el-collapse v-model="activeCollapseNames">
					<el-collapse-item title="展开更多" name="more">
						<!-- 门店 -->
						<el-form-item label="参与门店：" prop="shop">
							<el-radio v-model="form.shopRadioExtra" :label="1">全部门店</el-radio>
							<br />
							<el-radio v-model="form.shopRadioExtra" :label="2" style="margin-right:10px">指定门店使用</el-radio>
							<el-button :disabled="form.shopRadioExtra !== 2" @click="openShopTree(form.shop)">
								已选择&nbsp;
								<span style="color:red">{{ form.shop.length }}</span>
								&nbsp;家门店
							</el-button>
						</el-form-item>
						<!-- 交易类型 -->
						<el-form-item label="参与交易类型：" prop="bizType">
							<el-radio v-model="form.bizTypeRadioExtra" :label="1">全部交易类型</el-radio>
							<br />
							<el-radio v-model="form.bizTypeRadioExtra" :label="2">指定交易类型可参与</el-radio>
							<br />
							<el-collapse-transition>
								<div v-if="form.bizTypeRadioExtra === 2" class="nest-card-box">
									<el-card>
										<el-checkbox-group v-model="form.bizType">
											<template v-for="item in manageBizCodeOptions">
												<el-checkbox
													v-if="(item.usePay && item.canDiscount) || (form.activityType === 3 && item.key === 9001)"
													:key="item.value"
													:label="String(item.key)"
												>
													{{ item.label }}
												</el-checkbox>
											</template>
										</el-checkbox-group>
									</el-card>
								</div>
							</el-collapse-transition>
						</el-form-item>
						<!-- 支付方式 -->
						<el-form-item label="参与支付方式：" prop="payType">
							<el-radio v-model="form.payTypeRadioExtra" :label="1">全部支付方式</el-radio>
							<br />
							<el-radio v-model="form.payTypeRadioExtra" :label="2">指定支付方式可参与</el-radio>
							<br />
							<el-collapse-transition>
								<div v-if="form.payTypeRadioExtra === 2" class="nest-card-box">
									<el-card>
										<el-checkbox-group v-model="form.payType">
											<el-checkbox v-for="item in paymentOptions" :key="item.key" :label="String(item.key)">{{ item.label }}</el-checkbox>
										</el-checkbox-group>
									</el-card>
								</div>
							</el-collapse-transition>
						</el-form-item>
						<el-form-item v-if="[3, 4].includes(form.activityType)" label="参与付款方式：" prop="bankCode">
							<el-radio v-model="form.limitPay" :label="1">全部付款方式</el-radio>
							<br />
							<el-radio v-model="form.limitPay" :label="2">指定银行卡</el-radio>
							<br />
							<el-radio v-model="form.limitPay" :label="3">排除支付银行卡</el-radio>
							<br />
							<el-collapse-transition>
								<div v-if="form.limitPay === 2 || form.limitPay === 3" class="nest-card-box">
									<el-transfer
										v-model="form.bankCode"
										:titles="['备选银行列表', '已选银行列表']"
										:props="{
											key: 'value',
											label: 'label'
										}"
										:data="wxPayBankCardOptions"
										filterable
									/>
								</div>
							</el-collapse-transition>
						</el-form-item>
						<el-form-item label="详情介绍：">
							<el-input
								v-model="form.remark"
								:autosize="{ minRows: 5, maxRows: 15 }"
								type="textarea"
								placeholder="请输入内容"
								maxlength="500"
								class="nest-card-box"
								show-word-limit
							/>
						</el-form-item>
					</el-collapse-item>
				</el-collapse>
			</div>
			<!-- 高级设置  结束-->

			<!-- 操作 -->
			<el-form-item>
				<el-button :disabled="loading" type="primary" round @click="save">保 存</el-button>
				<el-button v-if="id" round @click="fetchData">重 置</el-button>
			</el-form-item>
		</el-form>

		<!-- 上传图片 -->
		<DialogUploadPhoneListKey ref="dialogUploadPhoneListKey" />
		<!-- 编辑规则 -->
		<DialogEditConsumeGiftRule ref="editConsumeGiftRule" />
		<!-- 选择可用门店弹框 -->
		<DialogShopListTree ref="dialogShopListTree" title="可用门店" @emitShopIds="emitShopIds" />
		<!--券2.0 筛选表格 -->
		<DialogCardCouponTable ref="dialogCardCouponTable" :has-checked-ids="hasCheckedCardCouponIds" />
		<!-- 营销商品库   -->
		<DialogMarketingGoodsTable ref="dialogMarketingGoodsTable" />
	</div>
</template>

<script>
import { wxPayBankCardOptions, wxPayBankNameOptions, wxPayBankCardTypeOptions } from '@/assets/json/wxpay-bank';
import DialogEditConsumeGiftRule from './DialogEditConsumeGiftRule';
import DialogUploadPhoneListKey from './DialogUploadPhoneListKey';
import ActivityFormValidate from './mixin/ActivityFormValidate';
import DialogCardCouponTable from '@/components/DialogCardCouponTable';
import DialogMarketingGoodsTable from '@/components/DialogMarketingGoodsTable';
import { mapGetters } from 'vuex';
import { imgUploadUrl } from '@/api/upload';
import { getAllVipCardList, getMemberGroups, judgeOpenRfm } from '@/api/vip';
import {
	addConsumeAward,
	getMemberDayConfigList,
	updateConsumeAward,
	addSingleItemActivity,
	updateSingleItemActivity,
	getActivityDetailById,
	modifyActivityStatus
} from '@/api/marketing';

export default {
	components: {
		DialogCardCouponTable,
		DialogEditConsumeGiftRule,
		DialogUploadPhoneListKey,
		DialogMarketingGoodsTable
	},
	mixins: [ActivityFormValidate],
	props: {
		// onlyMemberDay: {
		//   type: Boolean,
		//   required: false,
		//   default: false
		// },
		// activityType: {
		//   type: Number,
		//   required: false
		// }
	},
	data() {
		return {
			// 配置
			weekKeyOptions: ['', '周日', '周一', '周二', '周三', '周四', '周五', '周六'],
			weekOptions: [
				{ value: '周一', label: 2 },
				{ value: '周二', label: 3 },
				{ value: '周三', label: 4 },
				{ value: '周四', label: 5 },
				{ value: '周五', label: 6 },
				{ value: '周六', label: 7 },
				{ value: '周日', label: 1 }
			],
			actionUrl: imgUploadUrl, // 上传地址
			activeCollapseNames: '',
			datePickerOptions: {
				disabledDate: time => {
					return this.setDisabledDate(time);
				}
			},
			wxPayBankCardOptions: wxPayBankCardOptions,
			wxPayBankNameOptions: wxPayBankNameOptions,
			wxPayBankCardTypeOptions: wxPayBankCardTypeOptions,
			// 状态值
			loading: false,
			// 数据
			id: '',
			timeState: '',
			hasCheckedCardCouponIds: [], // 当前所有规则默认已选择的优惠券
			cardList: [], // 卡列表
			memberDayList: [], // 会员日列表
			form: {
				activityType: 1, //  1.消费赠礼 2.返零钱  3.返红包  4.领券
				onlyMemberDay: false, // 是否是会员日专享
				theme: '', // 主题
				image: '', // 海报
				date: '', // 活动日期 no params  转{startTime，endTime}
				useRule: 1, // 日期类型
				ruleDataWeek: [], // 有效周
				ruleDataTime: [{ time: ['00:00', '23:59'] }], // 有效时间
				ruleDataDate: [{ date: '' }], // 有效日期
				participant: 1, // 面向类型
				memberCategory: [], // 面向对象
				specificBank: null, // 银行名称
				phoneListKey: null, // 上传文件code
				matchPrecision1: null, // 匹配手机精度
				matchPrecision2: null, // 匹配银行精度
				calculateTypeExtra: 1, //  赠送规则类型 1：阶梯 2：每满
				award: [], // 赠送规则
				singleGoods: null, // 单品营销商品
				singleRules: [
					{
						everyOne: false,
						threshold: null,
						amount: null
					}
				], // 单品营销规则
				discountSharing: false,
				wxMchId: null, // 商户mchId
				appId: null, // 微信Appid
				sender: null, // 发送者
				blessing: null, // 祝福语
				frequencyDay: '', // 用户日限制
				frequencyDayCheckedExtra: false, //  用户日预算  no params  转{frequencyDay}
				frequencyWeek: '', //  用户周预算
				frequencyWeekCheckedExtra: false, //  用户周预算  no params  转{frequencyWeek}
				frequencyMonth: '', //  用户月预算
				frequencyMonthCheckedExtra: false, //  用户月预算  no params  转{frequencyMonth}
				frequencyAll: '', //  用户总预算
				frequencyAllCheckedExtra: false, //  用户总预算
				budget: '', // 活动总预算
				budgetCheckedExtra: false, // 活动总预算  no params  转{budget}
				perdayBudget: '', // 活动日预算
				perdayBudgetCheckedExtra: false, // 活动日预算  no params  转{perdayBudget}
				shop: [], // 参与门店
				shopRadioExtra: 1, // 参与门店 no params  转{shop}
				bizType: [], // 交易类型
				bizTypeRadioExtra: 1, // 交易类型 no params  转{bizType}
				payType: [], // 支付方式
				payTypeRadioExtra: 1, // 支付类型 no params  转{payType}
				bankCode: [], // 支付银行  转,号分割string
				limitPay: 1, // 1 全部  2指定银行  3排除银行
				remark: '', // 备注
				status: 1 // 活动状态，1：启用，2：暂停，3：已终止
			},
			memberGroup: [
				{ value: '0', label: '活跃会员', checked: false },
				{ value: '1', label: '预流失会员', checked: false },
				{ value: '2', label: '流失会员', checked: false },
				{ value: '3', label: '未转化会员', checked: false },
				{ value: '4', label: '未复购会员', checked: false },
				{ value: '5', label: '加购未支付会员', checked: false },
				{ value: '6', label: '下单未支付会员', checked: false }
			], // 会员分群
			judgeOpen: null
		};
	},
	computed: {
		...mapGetters(['fileBaseUrl', 'manageBizCodeOptions', 'paymentOptions', 'features'])
	},
	mounted() {
		this.id = this.$route.query.id || '';
		this.timeState = this.$route.query.timeState || '';
		if (!this.id) {
			this.form.onlyMemberDay = !!JSON.parse(this.$route.query.onlyMemberDay);
			this.form.activityType = Number(this.$route.query.activityType) || 1;
			if (this.form.onlyMemberDay) this.form.participant = 2;
		}
		this.fetchData();
		this.judgeOpenRfmFun();
	},
	methods: {
		/**
		 * 获取数据
		 */
		// 初始化数据
		async fetchData() {
			this.loading = true;
			await this.getDetail();
			Promise.all([this.getCardList(), this.getMemberDayList()]).finally(() => {
				this.loading = false;
			});
		},

		// 获取活动表单
		getDetail() {
			return new Promise(resolve => {
				if (this.id) {
					getActivityDetailById({ id: this.id })
						.then(res => {
							// 重置回表单数据
							let data = {};
							data = res.data.activity;
							data.award = res.data.awards || [];
							data.singleGoods = res.data.goodsCodes || [];
							data.singleRules = res.data.singleItemRules || [];
							this.formatData(data, resolve);
						})
						.finally(() => {
							resolve();
						});
				} else {
					resolve();
				}
			});
		},

		// 获取会员卡
		getCardList() {
			return new Promise((resolve, reject) => {
				getAllVipCardList().then(res => {
					this.cardList = res.data;
					resolve();
				});
			});
		},

		// 获取会员卡
		getMemberDayList() {
			return new Promise((resolve, reject) => {
				if (this.form.onlyMemberDay) {
					getMemberDayConfigList().then(res => {
						this.memberDayList = res.data;
						resolve();
					});
				} else {
					resolve();
				}
			});
		},

		// 格式化数据
		formatData(data, resolve) {
			data.date = [data.startTime, data.endTime];
			if (data.useRule === 1) {
				data.ruleDataTime = [{ time: ['00:00', '23:59'] }];
				data.ruleDataDate = [{ date: '' }];
				data.ruleDataWeek = [];
			} else {
				const ruleDataDateArr = [];
				const ruleDataTimeArr = [];
				data.ruleDataTime = data.ruleDataTime.split(',');
				data.ruleDataTime.forEach(v => {
					ruleDataTimeArr.push({
						time: [this.$options.filters.minsToHourMins(v.split('-')[0]), this.$options.filters.minsToHourMins(v.split('-')[1])]
					});
				});
				data.ruleDataTime = ruleDataTimeArr;
				switch (data.useRule) {
					case 2:
						data.ruleDataWeek = data.ruleDataWeek.split(',');
						data.ruleDataDate = [{ date: '' }];
						break;
					case 3:
						data.ruleDataTime = [{ time: ['00:00', '23:59'] }];
						data.ruleDataDate = data.ruleDataDate.split(',');
						data.ruleDataDate.forEach(v => {
							ruleDataDateArr.push({
								date: [v.split(':')[0], v.split(':')[1]]
							});
						});
						data.ruleDataDate = ruleDataDateArr;
						data.ruleDataWeek = [];
						break;
				}
			}

			// 参与对象:
			// data.memberCategory = data.participant !== 3 ? [] : data.memberCategory.split(',')
			data.memberCategory = data.memberCategory.split(',');

			switch (data.activityType) {
				case 1:
				case 2:
				case 3:
				case 4:
					// 精度
					if (data.activityType === 4) {
						if ((data.participant === 4 || data.participant === 5) && data.matchPrecision) {
							data.matchPrecision1 = data.matchPrecision.split(',')[0] || null;
							data.matchPrecision2 = data.matchPrecision.split(',')[1] || null;
						} else {
							data.matchPrecision1 = null;
							data.matchPrecision2 = null;
						}
					}
					// 奖励规则
					data.calculateTypeExtra = data.award[0].calculateType;
					data.award.forEach(v => {
						v.awardTypeExtra = [];
						// 消费金额
						v.amount = v.amount / 100;
						// 余额
						if (v.bonusBalance) {
							v.awardTypeExtra.push('bonusBalance');
							v.balance = v.balance / 100;
						}
						//  积分
						if (v.bonusPoint) {
							v.awardTypeExtra.push('bonusPoint');
						}
						// 券
						if (v.bonusCoupon) {
							v.awardTypeExtra.push('bonusCoupon');
							v.couponData = JSON.parse(v.couponData);
						} else {
							v.couponData = [];
						}
					});
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					data.singleRules.forEach(v => {
						if (data.activityType === 5) {
							v.threshold = this.$math.div(v.threshold, 100, 2);
							v.amount = this.$math.div(v.amount, 100, 2);
						}
						if (data.activityType === 7) {
							v.amount = this.$math.div(v.amount, 10, 1);
						}
						if (data.activityType === 8) {
							v.amount = this.$math.div(v.amount, 100, 2);
						}
					});
					data.singleGoods = data.singleGoods.join(',').replace(/,/g, '\r\n');
					break;
			}

			// 用户日预算
			if (data.frequencyDay === -1) {
				data.frequencyDayCheckedExtra = false;
				data.frequencyDay = '';
			} else {
				data.frequencyDayCheckedExtra = true;
			}

			// 用户周总预算
			if (data.frequencyWeek === -1) {
				data.frequencyWeekCheckedExtra = false;
				data.frequencyWeek = '';
			} else {
				data.frequencyWeekCheckedExtra = true;
			}

			// 用户月预算
			if (data.frequencyMonth === -1) {
				data.frequencyMonthCheckedExtra = false;
				data.frequencyMonth = '';
			} else {
				data.frequencyMonthCheckedExtra = true;
			}

			// 用户总预算
			if (data.frequencyAll === -1) {
				data.frequencyAllCheckedExtra = false;
				data.frequencyAll = '';
			} else {
				data.frequencyAllCheckedExtra = true;
			}

			// 总预算
			if (data.budget === -1) {
				data.budgetCheckedExtra = false;
				data.budget = '';
			} else {
				data.budgetCheckedExtra = true;
			}

			// 单天活动预算
			if (data.perdayBudget === -1) {
				data.perdayBudgetCheckedExtra = false;
				data.perdayBudget = '';
			} else {
				data.perdayBudgetCheckedExtra = true;
			}

			// 门店
			if (data.shop) {
				data.shopRadioExtra = 2;
				// data.shop = data.shop.split(",");
				data.shop = data.shop.split(',').map(function(data) {
					return +data;
				});
			} else {
				data.shopRadioExtra = 1;
				data.shop = [];
			}

			// 交易类型
			if (data.bizType) {
				data.bizTypeRadioExtra = 2;
				data.bizType = data.bizType.split(',');
			} else {
				data.bizTypeRadioExtra = 1;
				data.bizType = [];
			}

			// 支付方式
			if (data.payType) {
				data.payTypeRadioExtra = 2;
				data.payType = data.payType.split(',');
			} else {
				data.payTypeRadioExtra = 1;
				data.payType = [];
			}

			// 付款方式
			if (data.limitPay) {
				switch (data.limitPay) {
					case 1:
						data.bankCode = [];
						break;
					case 2:
					case 3:
						data.bankCode = data.bankCode ? data.bankCode.split(',') : [];
						break;
				}
			} else {
				data.limitPay = 1;
				data.bankCode = [];
			}

			this.form = data;
			resolve();
		},

		/**
		 * 按钮组
		 */
		// 打开券详情
		openCouponDetail(id) {
			this.$refs.couponDetail.open(id);
		},

		// 返回
		back() {
			this.$router.go(-1);
			if (this.id) {
				this.$router.push({
					name: 'MarketingActivityManage',
					params: { timeState: this.timeState }
				});
			} else {
				this.$router.push({
					name: 'MarketingActivityCreate'
				});
			}
		},

		// 上传前处理
		beforeUploadImage(file) {
			return this.beforeUploadImg(file, this, 0, 0, 1);
		},

		// 图片上传
		uploadImageSuccess(res, file) {
			if (res.code === 0) {
				this.form.image = res.data.path;
				this.$refs.form.clearValidate(['image']);
			} else {
				this.$message.error(res.msg);
			}
		},

		// 新增时间
		addAvailablePeriodTime() {
			this.form.ruleDataTime.push({ time: '' });
		},

		// 删除时间
		delAvailablePeriodTime(index) {
			this.form.ruleDataTime.splice(index, 1);
			this.$refs.form.validateField('ruleDataTime');
		},

		// 新增日期
		addAvailablePeriodDate() {
			this.form.ruleDataDate.push({ date: '' });
		},

		// 删除时间
		delAvailablePeriodDate(index) {
			this.form.ruleDataDate.splice(index, 1);
			this.$refs.form.validateField('ruleDataDate');
		},

		// 新增规则
		addRuleRow() {
			console.log(this.form);
			switch (this.form.activityType) {
				// 消费赠礼
				case 1: {
					const amountArr = [];
					this.form.award.map(v => {
						amountArr.push(Number(v.amount));
					});
					this.$refs.editConsumeGiftRule
						.open({
							mode: 'add',
							calculateType: this.form.calculateTypeExtra,
							amountArr: amountArr
						})
						.then(res => {
							console.log(res);
							this.form.award.push(res);
							this.$refs.form.clearValidate(['award']);
						});
					break;
				}

				// 红包活动
				case 3:
					this.form.award.push({
						amount: null,
						awardTypeExtra: ['bonusBalance'],
						balance: null,
						calculateType: null,
						couponData: null,
						points: null
					});
					this.$refs.form.clearValidate(['award']);
					break;
				//  领券活动
				case 4:
					this.hasCheckedCardCouponIds = [];
					if (this.form.award.length) {
						this.form.award[0].couponData.forEach(v => {
							this.hasCheckedCardCouponIds.push(v.couponId);
						});
					}
					this.$nextTick(() => {
						this.$refs.dialogCardCouponTable.open().then(res => {
							res.forEach(v => {
								v.name = v.couponName;
								v.num = v.amount;
								delete v.couponName;
								delete v.amount;
							});
							res = JSON.parse(JSON.stringify(res));
							if (this.form.award.length) {
								this.form.award[0].couponData.push(...res);
							} else {
								const params = {
									amount: 0,
									awardTypeExtra: ['bonusCoupon'],
									balance: null,
									calculateType: null,
									couponData: res,
									points: null
								};
								this.form.award.push(params);
							}
							this.$refs.form.clearValidate(['award']);
						});
					});
					break;
				// 单品活动
				case 5:
				case 6:
				case 7:
				case 8:
					{
						const params = {
							everyOne: false,
							threshold: null,
							amount: null
						};
						this.form.singleRules.push(params);
					}
					break;
			}
		},

		// 编辑规则
		editRuleRow(index, row) {
			const amountArr = [];
			this.form.award.map((v, i) => {
				if (index !== i) {
					amountArr.push(Number(v.amount));
				}
			});
			this.$refs.editConsumeGiftRule
				.open({
					mode: 'edit',
					amountArr: amountArr,
					row
				})
				.then(res => {
					this.form.award[index] = res;
					this.form.award = JSON.parse(JSON.stringify(this.form.award));
				});
		},

		// 删除规则
		delRuleRow(index) {
			switch (this.form.activityType) {
				case 1:
				case 2:
				case 3:
					this.form.award.splice(index, 1);
					this.$nextTick(() => {
						this.$refs.form.validateField(['award']);
					});
					break;
				case 4:
					this.form.award[0].couponData.splice(index, 1);
					this.$nextTick(() => {
						this.$refs.form.validateField(['award']);
					});
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					this.form.singleRules.splice(index, 1);
					this.$nextTick(() => {
						this.$refs.form.validateField(['singleRules']);
					});
					break;
			}
		},

		// 修改预算
		// modifyQuantity(mode = "add") {
		//   let tipsText = "";
		//   if (mode === "add") {
		//     tipsText = "当前预算：1000（最多可增加9999）";
		//   } else {
		//     tipsText = "当前预算：1000（最多可减少9999）";
		//   }
		//   this.$prompt(
		//     tipsText,
		//     `请输入${mode == "add" ? "新增" : "减少"}预算数量`,
		//     {
		//       confirmButtonText: "保存",
		//       cancelButtonText: "取消",
		//       roundButton: true,
		//       inputValidator: this.validateQuantity
		//     }
		//   )
		//     .then(({ value }) => {})
		//     .catch(() => {});
		// },

		// 校验预算数量
		// validateQuantity(val) {
		//   if (val === '') {
		//     return '请输入数量'
		//   } else if (!/^[1-9]\d*$/.test(val)) {
		//     return '请输入正整数'
		//   } else if (val - 100 > 1000) {
		//     return '超过最大值'
		//   }
		// },

		// 会员分群
		judgeOpenRfmFun() {
			judgeOpenRfm().then(res => {
				this.judgeOpen = res.data;
				if (this.judgeOpen == 1) {
					this.getMemberGroupsFun();
				}
			});
		},
		getMemberGroupsFun() {
			getMemberGroups().then(res => {
				const memberGroup = res.data;
				for (let i = 0; i < memberGroup.length; i++) {
					const config = memberGroup[i].groupConfigs;
					const id = memberGroup[i].id;
					if (i == 0) {
						memberGroup[i].txt = `近${config[0].conditionValue}天有消费`;
					} else if (i == 1) {
						memberGroup[i].txt = `近${config[0].conditionValue}天有消费；近${config[1].conditionValue}天无消费`;
					} else if (i == 2) {
						memberGroup[i].txt = `近${config[0].conditionValue}天有消费；近${config[1].conditionValue}天无消费`;
					} else if (i == 3) {
						memberGroup[i].txt = `入会以来未完成消费`;
					} else if (i == 4) {
						memberGroup[i].txt = `入会以来仅完成1次消费`;
					} else if (i == 5) {
						memberGroup[i].txt = `近${config[0].conditionValue}天有加过购物车；近${config[1].conditionValue}天无消费`;
					} else if (i == 6) {
						memberGroup[i].txt = `近${config[0].conditionValue}天有下过单；近${config[1].conditionValue}天无消费`;
					}
				}
				this.memberGroup = memberGroup;
			});
		},
		judgeOpenBtn() {
			this.$router.push({
				name: 'PlugCenterList'
			});
		},

		// 打开上传文件
		openDialogUploadPhoneListKey(type) {
			this.$refs.dialogUploadPhoneListKey.open(type).then(res => {
				this.form.phoneListKey = res;
				this.$refs.form.clearValidate(['phoneListKey']);
			});
		},

		// 打开商品库
		openDialogMarketingGoodsTable() {
			this.$refs.dialogMarketingGoodsTable.open({ hasCheckedIds: [] }).then();
		},

		// 打开选择门店
		openShopTree() {
			console.log(this.form.shop);
			this.$refs.dialogShopListTree.open(this.form.shop);
		},

		// 选择可用门店
		emitShopIds(ids) {
			this.form.shop = ids;
			this.$refs.dialogShopListTree.hide();
		},

		// 保存
		save() {
			this.$refs.form.validate((valid, object) => {
				if (!valid) {
					Object.keys(object).some((v, i) => {
						if (['shop', 'bizType', 'payType', 'bankCode'].includes(v)) {
							this.activeCollapseNames = 'more';
							return true;
						}
					});
				} else {
					const data = JSON.parse(JSON.stringify(this.form));
					// 日期格式
					if (data.useRule === 1) {
						data.startTime = data.date[0];
						data.endTime = data.date[1];
						data.ruleDataWeek = '';
						data.ruleDataDate = '';
						data.ruleDataTime = '';
					} else {
						data.startTime = data.date[0];
						data.endTime = data.date[1];
						const ruleDataDateArr = [];
						const ruleDataTimeArr = [];
						data.ruleDataTime.forEach(v => {
							v.time[0] = this.$momentMini.duration(v.time[0]).asMinutes();
							v.time[1] = this.$momentMini.duration(v.time[1]).asMinutes();
							let timeStr = '';
							timeStr = v.time.join('-');
							ruleDataTimeArr.push(timeStr);
						});
						data.ruleDataTime = ruleDataTimeArr.join(',');
						switch (data.useRule) {
							case 2:
								data.ruleDataWeek = data.ruleDataWeek.sort().join(',');
								data.ruleDataDate = '';
								break;
							case 3:
								data.ruleDataWeek = '';
								data.ruleDataDate.forEach(v => {
									let dateStr = '';
									dateStr = v.date.join(':');
									ruleDataDateArr.push(dateStr);
								});
								data.ruleDataDate = ruleDataDateArr.join(',');
								break;
						}
					}

					// 参与对象
					// data.memberCategory = data.participant !== 3 ? '' : data.memberCategory.join(',')
					data.memberCategory = data.memberCategory.join(',');

					// 用户日预算
					if (!data.frequencyDayCheckedExtra) data.frequencyDay = -1;

					// 用户周总预算
					if (!data.frequencyWeekCheckedExtra) data.frequencyWeek = -1;

					// 用户月预算
					if (!data.frequencyMonthCheckedExtra) data.frequencyMonth = -1;

					// 用户总预算
					if (!data.frequencyAllCheckedExtra) data.frequencyAll = -1;

					// 总预算
					if (!data.budgetCheckedExtra) data.budget = -1;

					// 单天活动预算
					if (!data.perdayBudgetCheckedExtra) data.perdayBudget = -1;

					// 门店
					data.shop = data.shopRadioExtra === 1 ? '' : data.shop.join(',');

					// 交易类型
					data.bizType = data.bizTypeRadioExtra === 1 ? '' : data.bizType.join(',');

					// 支付方式
					data.payType = data.payTypeRadioExtra === 1 ? '' : data.payType.join(',');

					// 付款方式
					switch (data.limitPay) {
						case 1:
							data.bankCode = '';
							break;
						case 2:
						case 3:
							data.bankCode = data.bankCode.join(',');
							break;
					}

					delete data['date'];

					delete data['frequencyDayCheckedExtra'];
					delete data['frequencyWeekCheckedExtra'];
					delete data['frequencyMonthCheckedExtra'];
					delete data['frequencyAllCheckedExtra'];
					delete data['budgetCheckedExtra'];
					delete data['perdayBudgetCheckedExtra'];
					delete data['shopRadioExtra'];
					delete data['bizTypeRadioExtra'];
					delete data['payTypeRadioExtra'];
					delete data['issued'];
					const params = {};
					switch (data.activityType) {
						case 1:
						case 2:
						case 3:
						case 4:
							// 精度
							if (data.activityType === 4) {
								if (data.participant === 4) {
									data.matchPrecision = `${data.matchPrecision1},20`;
								} else if (data.participant === 5) {
									data.matchPrecision = `${data.matchPrecision1},${data.matchPrecision2}`;
								} else {
									data.matchPrecision = null;
								}
							}
							// 奖励规则
							data.award.forEach(v => {
								v.calculateType = data.calculateTypeExtra;
								// 消费金额
								v.amount = v.amount ? this.$math.mul(v.amount, 100, 0) : 0;
								// 余额
								if (v.awardTypeExtra.includes('bonusBalance')) {
									v.bonusBalance = true;
									v.balance = this.$math.mul(v.balance, 100, 0);
								} else {
									v.bonusBalance = false;
									v.balance = 0;
								}
								//  积分
								if (v.awardTypeExtra.includes('bonusPoint')) {
									v.bonusPoint = true;
								} else {
									v.bonusPoint = false;
									v.points = 0;
								}
								// 券
								if (v.awardTypeExtra.includes('bonusCoupon') || v.awardTypeExtra.includes('bonusCardCoupon')) {
									v.bonusCoupon = true;
									v.couponData = JSON.stringify(v.couponData);
								} else {
									v.bonusCoupon = false;
									v.couponData = '';
								}
								delete v['awardTypeExtra'];
							});
							delete data['calculateTypeExtra'];
							params.activity = data;
							params.award = data.award;
							break;
						case 5:
						case 6:
						case 7:
						case 8:
							data.singleRules.forEach(v => {
								if (data.activityType === 5) {
									v.threshold = this.$math.mul(v.threshold, 100, 0);
									v.amount = this.$math.mul(v.amount, 100, 0);
								}
								if (data.activityType === 7) {
									v.amount = this.$math.mul(v.amount, 10, 0);
								}
								if (data.activityType === 8) {
									v.amount = this.$math.mul(v.amount, 100, 0);
								}
							});
							params.activity = data;
							params.goodsCode = data.singleGoods
								.trim()
								.replace(/\r\n|\n|\r/g, ',')
								.replace(/,+/g, ',')
								.split(',');
							params.goodsCode = [...new Set(params.goodsCode)];
							params.rules = data.singleRules;
							break;
					}
					delete params.activity['award'];
					delete params.activity['singleGoods'];
					delete params.activity['singleRules'];

					// 更新
					console.log(params);
					if (this.id) {
						this.updateActivity(params);
					} else {
						this.addConfirm(params);
					}
				}
			});
		},

		// 保存确认
		addConfirm(params) {
			this.$confirm(
				'<div style="text-align: left">保存并启用：活动将在有效期内生效；</div><div style="text-align: left">仅保存：稍后在活动管理页手动开启; </div>',
				'温馨提示',
				{
					confirmButtonText: '保存并启用',
					cancelButtonText: '仅保存',
					type: 'warning',
					center: true,
					roundButton: true,
					dangerouslyUseHTMLString: true
				}
			)
				.then(async () => {
					this.loading = true;
					const id = await this.addActivity(params);
					this.changeStatus(id);
				})
				.catch(() => {
					this.loading = true;
					this.addActivity(params).then(() => {
						this.$notify({
							title: '成功',
							message: '保存成功',
							type: 'success',
							duration: 2000,
							offset: 40
						});
						this.loading = false;
						this.back();
					});
				});
		},

		// 新增
		addActivity(params) {
			let apiFun = addConsumeAward;
			switch (params.activity.activityType) {
				case 1:
				case 2:
				case 3:
				case 4:
					apiFun = addConsumeAward;
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					apiFun = addSingleItemActivity;
					break;
			}
			return new Promise((resolve, reject) => {
				apiFun(params)
					.then(res => {
						resolve(res.data);
					})
					.catch(() => {
						this.loading = false;
					})
					.finally(() => {});
			});
		},

		// 更新
		updateActivity(params) {
			this.loading = true;
			let apiFun = updateConsumeAward;
			switch (params.activity.activityType) {
				case 1:
				case 2:
				case 3:
				case 4:
					apiFun = updateConsumeAward;
					break;
				case 5:
				case 6:
				case 7:
				case 8:
					apiFun = updateSingleItemActivity;
					break;
			}
			apiFun(params)
				.then(() => {
					this.$notify({
						title: '成功',
						message: '更新成功',
						type: 'success',
						duration: 2000,
						offset: 40
					});
					this.back();
				})
				.finally(() => {
					this.loading = false;
				});
		},

		// 更新状态
		changeStatus(id) {
			return new Promise((resolve, reject) => {
				const params = {
					activityId: id,
					status: 1
				};
				modifyActivityStatus(params)
					.then(res => {
						this.$notify({
							title: '成功',
							message: '保存成功并已启用',
							type: 'success',
							duration: 2000,
							offset: 40
						});
						this.back();
					})
					.catch(() => {
						this.$notify({
							title: '失败',
							message: '启用失败',
							type: 'success',
							duration: 2000,
							offset: 40
						});
						this.back();
					})
					.finally(() => {
						this.loading = false;
					});
			});
		},

		// 跳转会员日设置
		jumpVipBenefitMemberDay() {
			this.$router.push({
				name: 'VipBenefitMemberDay'
			});
		},

		/**
		 * 方法组
		 */
		// 设置不可选日期
		setDisabledDate(time) {
			if (this.id && this.form.createTime) {
				return time.getTime() <= this.$momentMini(this.form.createTime).valueOf() - 86400000;
			} else {
				return time.getTime() < Date.now() - 86400000;
			}
		},

		/**
		 * 状态
		 */
		participantChange(val) {
			if (val === 4 || val === 5) {
				this.form.phoneListKey = null;
			}

			// 清空会员多选框
			this.form.memberCategory = [];
		},

		// everyOne变更
		everyOneChange(val) {
			this.form.singleRules.map(v => {
				v.everyOne = val;
			});
		}
	}
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 通用 */
.w-500 {
	width: 500px;
}

.w-200 {
	width: 150px;
}

.w-200 {
	width: 200px;
}

/* 提示 */
.tips-info {
	line-height: 1.5;
	font-size: 12px;
	color: #909399;
}

/* 上传图片 */
.upload-poster-img {
	width: 375px;
	height: 220px;

	.upload-icon-plus {
		font-size: 36px;
		color: #8c939d;
		width: 375px;
		height: 220px;
		line-height: 220px;
		text-align: center;
	}

	.upload-img {
		width: 375px;
		height: 220px;
		display: block;
	}
}

/* 日期盒子 */
::v-deep .el-form-item .date-picker-box {
	margin-top: 18px;
}

/* 奖励类型icon文字*/
.award-type-icon {
	display: inline-block;
	width: 18px;
	height: 18px;
	line-height: 18px;
	text-align: center;
	color: #fff;
}

.award-type-icon-balance {
	background-color: #f59a23;
}

.award-type-icon-point {
	background-color: #10aeff;
}

.award-type-icon-coupon {
	background-color: #fa5151;
}

/* 嵌套盒子 */
.nest-card-box {
	width: 80%;
	min-width: 800px;
	max-width: 1000px;

	::v-deep .el-card {
		margin-bottom: 10px;
	}
}

// 格式化el

::v-deep {
	.el-collapse-item__header {
		padding-left: 40px;
	}

	.el-transfer-panel {
		width: 290px;
	}
}
</style>
